package com.rc.saas.tenant.client;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.constant.RouterConfig;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.member.MemberInfoMapper;
import com.rc.saas.tenant.mapper.order.OrderInfoMapper;
import com.rc.saas.tenant.model.elec.ElecPileHost;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.service.elec.ElecPileHostService;
import com.rc.saas.tenant.common.utils.RestTemplateUtil;
import com.rc.saas.tenant.vo.elec.UnlockReq;
import com.rc.saas.tenant.vo.elec.UserAccountVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * Created by sven on 2019/12/13
 */
@Component
public class ChargerClientRouter {
    private static Logger logger = LogManager.getLogger(ChargerClientRouter.class);

    @Autowired
    private StdEvchargerClient1 stdEvchargerClient1;

    @Autowired
    private StdEvchargerClient2 stdEvchargerClient2;

    @Autowired
    private StdEvchargerClient3 stdEvchargerClient3;

    @Autowired
    private StdEvchargerClient4 stdEvchargerClient4;

    @Autowired
    private MutiEvchargerClient1 mutiEvchargerClient1;

    @Autowired
    private MutiEvchargerClient2 mutiEvchargerClient2;

    @Autowired
    private MutiEvchargerClient3 mutiEvchargerClient3;

    @Autowired
    private MutiEvchargerClient4 mutiEvchargerClient4;

    @Autowired
    private ElecPileHostService elecPileHostService;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    /**
     * 测试
     */
    public String test(String type, Long id) {
        try {
            if (type.equals("AAA")) {
                String aa = stdEvchargerClient1.test(id);
                logger.info("EurekaClientFeign 调用成功:{}", aa);

                return aa;
            }
        } catch (Exception e) {
            logger.error("EurekaClientFeign 调用失败", e);
        }

        return null;
    }

    /**
     * 解锁指令
     */
    public TResponse sendUnlock(UnlockReq unlockReq) {
        //桩群表的充电服务器域名DOMAIN1,DOMAIN2
//        if (elecServerDomain.equals(HttpConstant.STD_DOMAIN)) {//标准桩
//            switch (elecServerSpliter) {
//                case 0:
//                    return stdEvchargerClient1.sendUnlock(unlockReq);//37
//                case 1:
//                    return stdEvchargerClient2.sendUnlock(unlockReq);//221
//                case 2:
//                    return stdEvchargerClient3.sendUnlock(unlockReq);//73
//            }
//        } else {//智充桩
//            if (elecServerSpliter == 0) {
//                return mutiEvchargerClient1.sendUnlock(unlockReq);
//            }
//        }
//        return null;

        //查地址表
        ElecPileHost elecPileHost = elecPileHostService.selectByPrimaryKey(unlockReq.getPileId());

        //拼接eureka访问地址
        String requestUrl = RouterConfig.WECHAT_UNLOCK_PATH;
        if (HttpConstant.STD_DOMAIN.equals(elecPileHost.getElecServerDomain())) {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.STD_SERVICE_PATH + RouterConfig.WECHAT_UNLOCK_PATH;
        } else {
            return TResponse.FAIL("暂无非标桩的枪解锁功能");
//            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.MUL_SERVICE_PATH + RouterConfig.MUTI_WECHAT_UNLOCK_PATH;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String respData = null;
        try {
            respData = objectMapper.writeValueAsString(unlockReq);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JSONObject tRequestJson = JSONObject.parseObject(respData);

        logger.info("std入参加密接口,桩解锁接口被调用，...............对应url:{},orderSource:{}", requestUrl);
        //通过rest调用远程服务接口
        ResponseEntity<TResponse> request = restTemplateUtil.request(requestUrl, HttpMethod.POST, tRequestJson, TResponse.class);
        logger.info("std入参加密接口,桩解锁接口被调用，...............返回状态码:{},结果集:{}", request.getStatusCode(), request.getBody().toString());
        return request.getBody();
    }


    /**
     * 解锁指令
     */
    public TResponse sendUserAccount(Long memberId, String memberType) {

        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
        // 0 :个人 1:企业钱包
        //if ("0".equals(memberInfo.getMemberType())) {
        //    return TResponse.FAIL();
        //}
        OrderInfo orderInfo = orderInfoMapper.selectNewOrderByMemberId(memberId);
        if (orderInfo == null || "2".equals(orderInfo.getStatus())) {
            return TResponse.FAIL();
        }

        UserAccountVo userAccountVo = new UserAccountVo();
        userAccountVo.setMemberId(memberId);
        userAccountVo.setPileId(orderInfo.getElecPileId());
        userAccountVo.setOrderNum(orderInfo.getOrderNum());
        userAccountVo.setTenantCode(memberInfo.getTenantCode());

        //查地址表
        ElecPileHost elecPileHost = elecPileHostService.selectByPrimaryKey(userAccountVo.getPileId());

        //拼接eureka访问地址
        String requestUrl = RouterConfig.USER_ACCOUNT_PATH;
        if (HttpConstant.STD_DOMAIN.equals(elecPileHost.getElecServerDomain())) {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.STD_SERVICE_PATH + RouterConfig.USER_ACCOUNT_PATH;
        } else {
            return TResponse.FAIL("暂无非标桩的余额下发功能");
//            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.MUL_SERVICE_PATH + RouterConfig.MUTI_WECHAT_UNLOCK_PATH;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String respData = null;
        try {
            respData = objectMapper.writeValueAsString(userAccountVo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JSONObject tRequestJson = JSONObject.parseObject(respData);

        logger.info("std入参加密接口,余额下发接口被调用，...............对应url:{},orderSource:{}", requestUrl);
        //通过rest调用远程服务接口
        ResponseEntity<TResponse> request = restTemplateUtil.request(requestUrl, HttpMethod.POST, tRequestJson, TResponse.class);
        logger.info("std入参加密接口,余额下发接口被调用，...............返回状态码:{},结果集:{}", request.getStatusCode(), request.getBody().toString());
        return request.getBody();
    }

    /**
     * 后台结算订单（反向订单,自主订单）
     */
    public TResponse updateOrder(String elecServerDomain, int elecServerSpliter, Long orderId) {
        //桩群表的充电服务器域名DOMAIN1,DOMAIN2
        if (elecServerDomain.equals(HttpConstant.STD_DOMAIN)) {//标准桩
            switch (elecServerSpliter) {
                case 0:
                    return stdEvchargerClient1.updateOrder(orderId);
                case 1:
                    return stdEvchargerClient2.updateOrder(orderId);
                case 2:
                    return stdEvchargerClient3.updateOrder(orderId);
            }
        } else {
            return stdEvchargerClient2.updateOrder(orderId);
        }
        return TResponse.FAIL("后台结算订单失败");
    }

    /**
     * 后台结算订单（反向互联互通订单）
     */
    public TResponse updateOrderCostHlht1(String elecServerDomain, int elecServerSpliter, String tenantCode, Long orderId, String authorization) {
        //桩群表的充电服务器域名DOMAIN1,DOMAIN2
        if (elecServerDomain.equals(HttpConstant.STD_DOMAIN)) {//标准桩
            switch (elecServerSpliter) {
                case 0:
                    return stdEvchargerClient1.updateOrderCostHlht1(tenantCode, orderId, authorization);
                case 1:
                    return stdEvchargerClient2.updateOrderCostHlht1(tenantCode, orderId, authorization);
                case 2:
                    return stdEvchargerClient3.updateOrderCostHlht1(tenantCode, orderId, authorization);
            }
        } else {
            return stdEvchargerClient2.updateOrderCostHlht1(tenantCode, orderId, authorization);
        }
        return TResponse.FAIL("后台结算订单失败");
    }

    /**
     * 后台结算订单（正向互联互通订单）
     */
    public TResponse updateOrderCostHlht2(Long orderId) {
        return stdEvchargerClient1.updateOrderCostHlht2(orderId);
    }

}
